package testing;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import infrastructure.KVMessageImp;

import org.junit.Test;

import common.messages.KVMessage;
import common.messages.KVMessage.StatusType;

import junit.framework.TestCase;

public class AdditionalTest extends TestCase {
	
	// TODO add your test cases, at least 3
	
	@Test
	public void testMarshallUnmarshallFile() {
		String filePath = "testMarshall.xml";
		File file = null;
		KVMessage message = new KVMessageImp("testing", "testing2", StatusType.DELETE_ERROR);
		Exception ex = null;
		try {
			file = new File(filePath);			
			JAXBContext jaxbContext = JAXBContext.newInstance(KVMessageImp.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);	 
			jaxbMarshaller.marshal(message, file);			
			KVMessage message2 = (KVMessage) jaxbUnmarshaller.unmarshal(file);
			assertEquals(message.getKey(), message2.getKey());
			assertEquals(message.getValue(), message2.getValue());
			assertEquals(message.getStatus(), message2.getStatus());
		} catch (JAXBException e) {
			ex = e;
		}
		finally {
			if (file != null) {
				file.delete();
			}
		}
	
		assertNull(ex);
	}
	
	@Test
	public void testMarshallUnmarshallBytes() {
		ByteArrayOutputStream streamBytesOutput = new ByteArrayOutputStream();
		ByteArrayInputStream streamBytesInput = null;
		KVMessage message = new KVMessageImp("testing", "testing2", StatusType.GET_SUCCESS);
		Exception ex = null;
		try {			
			JAXBContext jaxbContext = JAXBContext.newInstance(KVMessageImp.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);	 
			jaxbMarshaller.marshal(message, streamBytesOutput);			
			streamBytesInput = new ByteArrayInputStream(streamBytesOutput.toByteArray());			
			KVMessage message2 = (KVMessage) jaxbUnmarshaller.unmarshal(streamBytesInput);			
			assertEquals(message.getKey(), message2.getKey());
			assertEquals(message.getValue(), message2.getValue());
			assertEquals(message.getStatus(), message2.getStatus());
		} catch (JAXBException e) {
			ex = e;
		} 
		finally {
			try {
				streamBytesOutput.close();
				streamBytesInput.close();
			} catch (IOException e) {
				ex = e;
			}
		}
	
		assertNull(ex);
	}
	
}